# -*- coding: UTF-8 -*-
from settings import logger
from tornado.httpclient import HTTPError


class Args(object):

    def __init__(self, controller, method, *argnames):
        self.controller = controller
        self.method = method
        self.args = {}
        self._init_args(argnames)

    def _init_args(self, argnames):
        for name in argnames:
            self.args[name] = self.controller.get_argument(name, '')
        if self.method == 'post':
            jsonbody = json.loads(self.controller.request.body.decode('utf-8'))
            for name in argnames:
                if not self.args[name]:
                    v = getattr(jsonbody, name, '')
                    self.args[name] = v if v else self.args[name]
        logger.info(self.args)

    def int_arg(self, argname, default):
        v = self.controller.get_argument(argname, default)
        try:
            v = int(v)
        except:
            v = default
        self.args[argname] = v

    def __getattr__(self, key):
        if key in self.args:
            return self.args[key]
        super().__getattr__(key)

    def validate(self):
        return True


class PageArgs(Args):
    
    def __init__(self, controller, method, *argnames):
        super().__init__(controller, method, *argnames)
        super().int_arg('pageNum', 1)
        super().int_arg('pageSize', 20)  

    def get_begin(self):
        return (self.args['pageNum'] - 1) * self.args['pageSize']

    def get_redis_stop(self):
        return self.get_begin() + self.args['pageSize'] - 1

    def get_stop(self):
        return self.pageNum * self.pageSize


